package com.lwj.yuangong2.controller;

import com.lwj.yuangong2.entity.User;
import com.lwj.yuangong2.service.UserService;
import com.lwj.yuangong2.utils.VerifyCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.Service;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin  //允许跨域 前后端分离
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 生成验证码图片
     */
    @GetMapping("/getImage")
    public  String getImageCode(HttpServletRequest request) throws IOException {
        //1.使用工具类生成验证码
        String code = VerifyCodeUtils.generateVerifyCode();
        //2.将验证码放入servletContext的作用域 暂时保存一下
        request.getServletContext().setAttribute("code",code);
        //3.将图片转为base64
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(120,30,byteArrayOutputStream,code);
        String  s = "data:image/png;base64,"+Base64Utils.encodeToString(byteArrayOutputStream.toByteArray());
        return s;
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Map<String ,Object> insertUser(@RequestBody User user, String code,HttpServletRequest request){

        //打印信息
        log.info("用户信息:[{}]",user.toString());
        log.info("用户输入的验证码:[{}]",code);
        
        Map<String,Object> map = new HashMap<>();
        try {
            String key= (String) request.getServletContext().getAttribute("code");
            if(key.equalsIgnoreCase(code)){
                userService.insertUser(user);
                map.put("state",true);
                map.put("msg","提示：注册成功!");
            }
            else {
                throw new  RuntimeException("验证码错误!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("state",false);
            map.put("msg","提示："+e.getMessage());
        }
        return map;
    }

    /**
     * 用户登录
     */
    @PostMapping("login")
    public Map<String,Object> login(@RequestBody User user){
        Map<String,Object> map = new HashMap<>();
        try {
            User userDB = userService.login(user);
            map.put("state",true);
            map.put("msg","登录成功");
            map.put("user",userDB);  //将登录成功的用户信息返回给前端
        } catch (Exception e) {
            map.put("state",false);
            map.put("msg",e.getMessage());
        }
        return map;
    }
}
